package com.mop.app.config;

import com.mop.app.global.GlobalResponseInitializer;
import com.mop.app.global.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.servlet.MultipartConfigElement;
import java.io.File;



@Configuration
public class WebConfiguration implements WebMvcConfigurer {
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Value("${smas.captrue.image.path}")
    private String captureImagePath;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize(DataSize.ofMegabytes(200));
        /// 总上传数据大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(200));
        //设置文件上传的临时目录，默认的临时目录会被清理掉导致上传时报临时目录不存在的异常
        String location = System.getProperty("user.dir") + "/data/tmp";
        System.out.println(location);

        File file = new File(uploadFolder);
        if (!file.exists()) {
            file.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("*").maxAge(3600);
//    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder + captureImagePath);
    }

    @Bean
    public GlobalResponseInitializer globalResponseInitializer(RequestMappingHandlerAdapter handlerAdapter) {
        return new GlobalResponseInitializer(handlerAdapter);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //静态资源不用管，springboot已做好
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/app/open/**")
                .excludePathPatterns("/login.html","/","/toindex","/toLogin","/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");

    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }


    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
//     请求常用的三种配置，*代表允许所有，当时你也可以自定义属性（比如header只能带什么，只能是post方式等等）
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

}
